package com.android.lovingpet.adopt.host.hostinfo.view;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.lovingpet.Application;
import com.android.lovingpet.R;
import com.android.lovingpet.adopt.host.hostinfo.HostInfoPresenter;
import com.android.lovingpet.adopt.host.hostinfo.IHostInfoContract;
import com.android.lovingpet.base.BaseFragment;
import com.android.lovingpet.bean.Host;
import com.android.lovingpet.bean.HostFoster;
import com.android.lovingpet.bean.Pet;
import com.android.lovingpet.mine.pet.view.PetRvAdapter;
import com.android.lovingpet.util.MyDatePickDialog;
import com.android.lovingpet.util.Utility;
import com.bumptech.glide.Glide;
import com.codbking.widget.bean.DateType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.android.lovingpet.adopt.host.hostinfo.HostInfoPresenter.FLAG_HOST_INFO;
import static com.android.lovingpet.adopt.host.hostinfo.HostInfoPresenter.FLAG_PET_INFO;
import static com.android.lovingpet.adopt.host.hostinfo.HostInfoPresenter.FLAG_Unused_PET_ID;

/**
 * Created by ikata on 2018/4/27.
 */

public class ContactWayFragment extends BaseFragment<IHostInfoContract.View, HostInfoPresenter> implements IHostInfoContract.View, View.OnClickListener {
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    Unbinder unbinder;
    @BindView(R.id.ll_beginTime)
    LinearLayout llBeginTime;
    @BindView(R.id.ll_endTime)
    LinearLayout llEndTime;
    @BindView(R.id.tv_beginTime)
    TextView tvBeginTime;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.ll_select_pet)
    LinearLayout llSelectPet;
    @BindView(R.id.bt_commit)
    Button btCommit;
    @BindView(R.id.iv_pet)
    ImageView ivPet;
    @BindView(R.id.tv_pet_name)
    TextView tvPetName;
    private Host host;
    private HostFoster hostFoster;
    private int petIdSelected = -1;

    private View dialogView;
    private PetRvAdapter petRvAdapter;
    private RecyclerView recyclerView;
    private AlertDialog petSelectedDialog;

    @Override
    protected int setContentView() {
        return R.layout.fragment_host_contact_way;
    }

    @Override
    protected void onCreateView(View view) {
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        setTitle(view, "联系方式");
    }

    @Override
    public HostInfoPresenter createPresenter() {
        return new HostInfoPresenter();
    }

    @Override
    public IHostInfoContract.View createView() {
        return this;
    }

    public void initView() {
        tvAddress.setText(host.getAddress());
        tvPhone.setText(host.getPhone());
        Glide.with(getContext())
                .load(host.getImage())
                .into(ivPhoto);

        //预加载我的宠物
        dialogView = View.inflate(Application.getContext(), R.layout.alert_pet_item, null);
        recyclerView = dialogView.findViewById(R.id.rv_pet_content);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        petRvAdapter = new PetRvAdapter(new ArrayList<>());
        recyclerView.setAdapter(petRvAdapter);
        petRvAdapter.setItemClickListener(position -> {
            petIdSelected = petRvAdapter.getPet(position).getId();
            Glide.with(getContext())
                    .load(petRvAdapter.getPet(position).getImage())
                    .into(ivPet);
            tvPetName.setText(petRvAdapter.getPet(position).getName());
            petSelectedDialog.dismiss();
        });
        getPresenter().getUnusedPetId(Utility.getRealId(), 1, 10);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.ll_beginTime, R.id.ll_endTime, R.id.bt_commit, R.id.ll_select_pet})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_beginTime:
                MyDatePickDialog.Builder builder = new MyDatePickDialog.Builder(getContext());
                builder.setYearLimit(1)
                        .setType(DateType.TYPE_ALL)
                        .setTitle("选择寄养的时间")
                        .setMessageFormat("yyyy-MM-dd HH:mm:ss")
                        .setOnSureLisener(date -> {
                            @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            tvBeginTime.setText(dateFormat.format(date));
                        }).build().show();

                break;
            case R.id.ll_endTime:
                MyDatePickDialog.Builder builder1 = new MyDatePickDialog.Builder(getContext());
                builder1.setYearLimit(1)
                        .setType(DateType.TYPE_ALL)
                        .setTitle("选择寄养的时间")
                        .setMessageFormat("yyyy-MM-dd HH:mm:ss")
                        .setOnSureLisener(date -> {
                            @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                if (date.after(dateFormat.parse(tvBeginTime.getText().toString()))) {
                                    tvEndTime.setText(dateFormat.format(date));
                                } else {
                                    Toast.makeText(getContext(), "请选择合适的时间！", Toast.LENGTH_LONG).show();
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                        }).build().show();
                break;
            case R.id.bt_commit:
                String beginTime = tvBeginTime.getText().toString();
                String endTime = tvEndTime.getText().toString();
                if ( petIdSelected == -1)
                {
                    Toast.makeText(getContext(),"请选择您要寄养的宠物!",Toast.LENGTH_LONG).show();
                    return;
                }
                if (hostFoster != null) {
                    getPresenter().updateInfo(beginTime, endTime, hostFoster.getFosterId(), petIdSelected);
                    break;
                }
                if (!TextUtils.isEmpty(beginTime) && !TextUtils.isEmpty(endTime)) {
                    getPresenter().fostersPet(host.getId(), petIdSelected, beginTime, endTime);
                    EventBus.getDefault().postSticky(petIdSelected);
                } else {
                    Toast.makeText(getContext(), "请填写完整的信息!", Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.ll_select_pet:
                ViewGroup viewGroup = (ViewGroup) recyclerView.getParent();
                if (viewGroup != null) {
                    viewGroup.removeAllViews();
                }
                AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext())
                        .setTitle("选择宠物")
                        .setView(dialogView);
                petSelectedDialog = builder2.create();
                petSelectedDialog.getWindow().getDecorView().setBackground(getContext().getDrawable(R.drawable.button_yj1));
                petSelectedDialog.show();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (hostFoster != null)
            EventBus.getDefault().removeStickyEvent(hostFoster);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void getHost(Host host) {
        this.host = host;
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void getHostFoster(HostFoster hostFoster) {
        this.hostFoster = hostFoster;
        getPresenter().getHostInfo(hostFoster.getHostId());
    }

    @Override
    public void next(@Nullable Bundle bundle) {
        if (bundle == null) {
            //处理寄养宠物
            getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.host_info_content, new FosterFinishFragment()).commit();
            //传递寄养的petid
            EventBus.getDefault().postSticky(petIdSelected);
            return;
        }
        int flag = bundle.getInt("flag");
        switch (flag) {
            case FLAG_HOST_INFO:
                host = bundle.getParcelable("result");
                runOnUiThread(() -> {
                    tvBeginTime.setText(hostFoster.getBeginTime());
                    tvEndTime.setText(hostFoster.getEndTime());
                });
                break;
            case FLAG_Unused_PET_ID:
                ArrayList<Integer> petIdList = bundle.getIntegerArrayList("ids");
                if (petIdList == null) {
                    Toast.makeText(getContext(), "都没有添加宠物，寄养个屁阿！", Toast.LENGTH_LONG).show();
                    return;
                }
                for (Integer id : petIdList) {
                    getPresenter().getPetInfo(id, 0);
                }
                //runOnUiThread(()->petRvAdapter.addPet(petList));
                break;
            case FLAG_PET_INFO:
                Pet pet = bundle.getParcelable("result");
                runOnUiThread(() -> petRvAdapter.addPet(pet));
                break;
        }


    }
}
